$(document).ready(function() {
    
  //Function to check all checkboxes
  $("#checkAll").click(function()	{
    var checked_status = this.checked;
    //get the list of checkbox and change the status to checked
    $("input[@name=checkBoxList]").each(function() {
      this.checked = checked_status;
    });
  });
		
  //Function to hide or show the filter box
  $("#edit-hide").click(function()	{
    if ($(".filter").is(":hidden")) {
      $(".filter").slideDown(); //show the filter if hidden
      $("#edit-hide").val("Hide"); //show the filter if hidden
    } else {
      $(".filter").slideUp(); //hide the filter
      $("#edit-hide").val("Show");
    }
    return false;
  });

  $(document).click(function(e){
    $('#moreactions').hide();
    $('#moreactions1').hide();
  })
	
  $("#edit-more-actions-common").click(function(){
    moreactions();
    return false;
  });
    
  if($(".test-action input").length>0){
    $(".test-action input").tooltip({
      track: true,
      delay: 3000,
      fixPNG: true,
      top: 15,
      left: 5
    });
  }
});

//Function for datepicker
function datePicker(obj){
  $('#'+obj).focus();
}

function createDatePicker(obj, min){
  $('#'+obj).datepicker({
    dateFormat:'mm-dd-yy',
    minDate: min,
    prevText: ''
  });
}
//Common function to open dialog box
function openDialog(module, id, width, height, title){
  $('#dialog').html('<div style="padding-top:'+(height/3-25)+'px; padding-left:'+(width/2-25)+'px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
  var wid = width;
  var heit = height;
  var buttons = false;
  $('#dialog').dialog({
    autoOpen: false,
    width: wid,
    height: heit,
    bgiframe: true,
    resizable: false,
    title:title,
    modal: true,
    show: 'puff',
    close: function () {
      $(this).dialog('destroy');
      $('#ui-datepicker-div').hide();
    }
  });
  $('#dialog').dialog('open');
  var h = heit;
  if(buttons){
    h = heit-95;
  }else{
    h = heit-40;
  }
  $('#dialog').css({
    'overflow-y':'auto',
    'width': (wid-16)+'px',
    'height':h+'px'
  }).show();

  if($.isFunction(module)){
    module(id);
    return;
  }
  if (module == "fulfillment") {
    fulfillmentDetails(id);
  }
  else if (module == "contactus") {
    contactusMessageDetails(id);
  }
  else if (module == "manage_subjects") {
    contactusSubjectDetails(id);
  }
  else if (module == "manage_requests") {
    requestTypeDetails(id);
  }
  else if(module == "autoreply"){
    manageautoreply();
  }
  //else if(module == "phupdatormail"){
  //phmanageautoreply();
  //}
  else if(module == "fulautoreply"){
    fulmanageautoreply();
  }
  else if(module == "createpoll"){
    createpolldialog();
  }
  else if(module == "serviceregistry"){
    createservicedialog();
  }
  else if(module == "createsurvey"){
    createsurveydialog();
  }
  else if(module == "survey"){
    surveyDetails(id);
  }
  else if(module == "datewisesurvey"){
    viewDateWiseReport();
  }else if (module == "testimonialarchived") {
    testimonialDetails(id+"/archived");
  }
  else if (module.indexOf("testimonial")>-1) {
    testimonialDetails(id);
  }
  else if(module == "poll/details"){
    viewpolldialog(id);
  }
  //else if(module == "serviceregistry/details"){
    //viewservicedialog(id);
  //}
  else if(module == "deletepoll"){
    deletepolldialog(id);
  }
  else if(module == "activatepoll"){
    activatepolldialog(id);
  }
  else if(module == "polleditquestion"){
    editquestionpolldialog(id);
  }
  else if(module == "savequestion"){
    savequestionpolldialog(id);
  }
  else if(module =="createnewsletter"){
    addEditNewsletter(id);
  }
  else if (module == "newsletter") {
    newsletterSubscriptionInfo(id);
  }
  //for assessment module
  else if(module == "createassessment") {
    createassessmentdialog();
  }
  else if(module == "assessment") {
    assessmentDetails(id);
  }
  else if(module == "editassessment") {
    editAssessmentDialog(id);
  }
  else if(module == "previewquestion_assessment") {
    previewAssessmentQuestionsDialog(id);
  }
  else if(module == "editquestion_assessment") {
    editAssessmentQuestionDialog(id);
  }
  else if(module == "editsinglequestion_assessment") {
    editSingleAssessmentQuestionDialog(id);
  }
  else if(module == "cloneassessment") {
    cloneAssessmentDialog(id);
  }
  else if(module == "assessmentreport") {
    viewassessmentreport(id);
  }
  else if(module == "autoresponse") {
    manageautoresponse();
  }
  //call subject reordering function
  else if(module == "reordersubjects") {
    reorderSubjects();
  }
  //call subject reordering function
  else if(module == "reorderassessmentquestions") {
    reorderQuestions(id);
  }
  //else if(module == "checkgroup") {
  //checkgroupdialog(id);
  //}
  //else if(module == "createphysician") {
  //createphysiciandialog();
  //}
  //else if(module == "addphysiciantoexistgroup") {
  //addphysiciantoexistgroupdialog(id, "");
  //}
  //else if(module == "addspeciality") {
  //addspecialitydialog();
  //}
  //else if(module == "addgroup") {
  //addgroupdialog();
  //}
  //else if(module == "assignspeciality") {
  //assignspecialitydialog();
  //}
  //else if(module == "addlocation") {
  //addlocationdialog();
  //}
  //else if(module == "viewphysician") {
  //viewphysiciandialog(id);
  //}
  //else if(module == "viewspeciality") {
  //viewspecialitydialog(id);
  //}
  //else if(module == "viewpatientdetails") {
  //viewpatientdetailsdialog(id);
  //}
  //else if (module == "HandoffSpecialities") {
  //Handoffspecialitiesdetails(id);
  //}
  //else if(module == "viewgroup") {
  //viewgroupdialog(id);
  //}
  //else if(module == "physiciansearch"){
  //physician_search_dialog();
  //}
  //else if(module == "physicians_view"){
  //physician_view_dialog(id);
  //}
  //else if(module == "addphysician"){
  //addphysician_view_dialog(id);
  //}
  else if(module == "addstore"){
    addStoredialog();
  }
  else if(module == "importstore"){
    importStoredialog();
  }
  else if(module == "addcategory"){
    addCategorydialog();
  }
  else if(module == "categoriesdetails"){
    categorydetailsDialoge(id);
  }
  else if(module == "storesdetails"){
    storedetailsDialoge(id);
  }
  //else if(module == "physicianstatus"){
  //physician_status_dialog();
  //}
  else if (module == "webmetrics") {
    graphInDialog(id);
  }
//}else if(module == "add_criteria"){
//criteriaDialog(id);
//}
//}else if(module == "physician_invitation"){
//physician_invitation();
//}
}

/* physician locator dialog starts here */



function editspecialitydialog(id){
  $.ajax({
    type : "GET",
    url : baseurl+'physician_locator/specialityedit/'+id,
    cache : false,
    success : function (res) {
      $('#dialog').html(res);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

function editgroupdialog(id){
  $.ajax({
    type : "GET",
    url : baseurl+'physician_locator/groupedit/'+id,
    cache : false,
    success : function (res) {
      $('#dialog').html(res);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

function viewspecalityPhysiciandialog(id){
  $.ajax({
    type : "GET",
    url : baseurl+'physician_locator/specialityaction/viewphysicians/'+id,
    cache : false,
    success : function (res) {
      $('#dialog').html(res);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

function viewspecalitySitesdialog(id){
  $.ajax({
    type : "GET",
    url : baseurl+'physician_locator/specialityaction/viewsites/'+id,
    cache : false,
    success : function (res) {
      $('#dialog').html(res);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}
/* physician locator dialog ends here */


//Function to get the individual fulfillment to display in detail page
function fulfillmentDetails (id) {
  $.ajax({
    type : "GET",
    url : baseurl+'fulfillment/details/'+id,
    cache : false,
    success : function (res) {
      $('#dialog').html(res);
			
      //ignore message in detail page
      $("#messagePopUpIngore").click(function() {
        openConfirmBox(function(){
          $("#alertdialog").dialog("destroy");
          ignoreArchiveMessages("", "ignore", id, "single", "popup");
        }, 300, 100, "Confirm Ignore", "Do you want to ignore this fulfillment?");
      });
			
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

//Function to get the individual testimonial to display in detail page
function testimonialDetails (id) {
  $.ajax({
    type : "GET",
    url : baseurl+'testimonial/details/'+id,
    cache : false,
    success : function (res) {
      $('#dialog').html(res);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

var editor;
function manageautoreply(){
  $.ajax({
    type : "GET",
    url : baseurl+'testimonial/manage_autoreply',
    cache : false,
    success : function (res) {
      $('#dialog').html(res);
      $('.ui-dialog').css("filter","");
      if(!editor){
        editor = CKEDITOR.replace( 'edit-resp-response',{
          skin : 'v2',
          resize_enabled:false,
          enterMode: Number(2),
          removePlugins : 'elementspath,save,forms,font,format,smiley,maximize,showblocks,about,stylescombo,pagebreak,flash'
        });
      }else{
        if (CKEDITOR.instances['edit-resp-response']) {
          CKEDITOR.remove(CKEDITOR.instances['edit-resp-response']);
        }
        editor = null;
        editor = CKEDITOR.replace( 'edit-resp-response',{
          skin : 'v2',
          resize_enabled:false,
          enterMode: Number(2),
          removePlugins : 'elementspath,save,forms,font,format,smiley,maximize,showblocks,about,stylescombo,pagebreak,flash'
        });
      }
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

function deletepolldialog(id){
  $('#dialog').dialog('destroy');
  openConfirmDialog ('polldelete', id, 500, 300, 'Delete Poll', 'Are you sure want to delete?', '')
}

function activatepolldialog(id){
  $.ajax({
    type : "GET",
    url : baseurl+'poll/activate/'+id,
    cache : false,
    success : function (res) {
      $('#dialog').html(res);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

function editquestionpolldialog(id){
  $('#dialog').html('<div style="padding-top:90px; padding-left:210px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
  $.ajax({
    type : "GET",
    url : baseurl+'poll/editquestions/'+id,
    cache : false,
    success : function (res) {
      $('#dialog').html(res);

      $("#edit-question-insert").click(function(){
        var l = $(this).position().left-1;
        var t = $(this).position().top+22;
        $('#moreactions1').css({
          'left':l+"px",
          'top':t+"px"
        }).slideDown();
        return false;
      });
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
  
}

function savequestionpolldialog(id){
  $('#dialog').dialog('destroy');
  openDialog("editpoll",id,500,255,"Poll Details");
  return false;
}

//Function to display the create poll page

function createpolldialog(){
  $('#dialog').html('<div style="padding-top:90px; padding-left:210px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
  $.ajax({
    type : "GET",
    url : baseurl+'poll/create_poll',
    cache : false,
    success : function (res) {
      $('#dialog').html(res);
      createDatePicker('edit-poll-expdate',0);
      createDatePicker('edit-poll-actdate',0);
      $("#createpoll_error").hide();
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

function createsurveydialog(){
  $.ajax({
    type : "GET",
    url : baseurl+'survey/edit/0',
    cache : false,
    success : function (res) {
      $('#dialog').html(res);
      createDatePicker('edit-survey-actdate',0);
      createDatePicker('edit-survey-expdate',0);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

function surveyDetails(id){
  $.ajax({
    type : "GET",
    url : baseurl+'survey/details/'+id,
    cache : false,
    success : function (res) {
      $('#dialog').html(res);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

function showMore(){
  var l = $('#more_actions').position().left-1;
  var t = $('#more_actions').position().top+22;
  if($.browser.msie)
    t-=6;
  $('#moreactions1').css({
    'left':l+"px",
    'top':t+"px"
  }).slideDown();
}

//Function to display more actions div on clicking more actions button
function moreactions(){
  var l = $('.test-action.more').position().left;
  var t = $('.test-action.more').position().top+23;
  $('#moreactions').css({
    'left':l+"px",
    'top':t+"px"
  }).slideDown();
}

//Function to get the chexkbox values as an array
function getSelectedValues () {
  var checkbox_values = [];
  $('input[@name=checkBoxList]:checked').each(function(i){
    checkbox_values[i] = $(this).val();//store the selected values in an array
  });

  return checkbox_values;
}

//Function to get the chexkbox values as an array
function getSelectedValues_Popup () {
  var checkbox_values = [];
  $('input[@name=checkBoxList_Popup]:checked').each(function(i){
    checkbox_values[i] = $(this).val();//store the selected values in an array
  });

  return checkbox_values;
}

//Function to get the chexkbox values as an array
function getAllValues_Popup () {
  var all_values = [];
  $('input[@name=checkBoxList_Popup]').each(function(i){
    all_values[i] = $(this).val();//store the selected values in an array
  });

  return all_values;
}

//Function to clear all the checkboxes selected
function clearCheckboxes () {
  $("input[@name=checkBoxList]").each(function() {
    this.checked = false;
  });
}

//function to open dialog box for alert messages
function openAlertDialog (width, height, title,  content, status) {
  var wid = width;
  var heit = height;
  var buttons = true;
  $('#alertdialog').dialog({
    autoOpen: false,
    width: wid,
    height: heit,
    bgiframe: true,
    resizable: false,
    title:title,
    modal: true,
    show: 'puff',
    close: function () {
      $('#alertdialog').dialog('destroy');
    },
    buttons: {
      'OK': function() { ////Previously it was Cancel
        $('#alertdialog').dialog('destroy');
      }
    }
  })
  $('#alertdialog').dialog('open');
  var h = heit;
  if(buttons){
    h = heit-80;
  }else{
    h = heit-60;
  }
  $('#alertdialog').css({
    'overflow-y':'auto',
    'width': (wid-15)+'px',
    'height':h+'px'
  }).show();
  var img_name = "warning.jpg"
  if(status && status=="success"){
    img_name = "correct.gif";
  }else if(status && status == 'information'){
    img_name = "triangle_blue_information.gif";
  }

  $('#alertdialog').html('<div style="padding-left: 0px;"><span style="float: left;"><img border="0" src="'+baseurl+themeurl+'/images/'+img_name+'"/></span><span style="float: left; padding-left: 10px; padding-top: 10px;width: '+(wid-50-20-25)+'px;">'+content+'</span></div>');
}

//function to open dialog box for alert messages
function openConfirmDialog (fn, id, width, height, title, content, mode) {
  var wid = width;
  var heit = height;
  var buttons = false;
  $('#dialog').dialog({
    autoOpen: false,
    width: wid,
    height: heit,
    bgiframe: true,
    resizable: false,
    title:title,
    modal: true,
    show: 'puff',
    close: function () {
      $('input[@name=checkBoxList]:checked').each(function(){
        this.checked = false;
      });
      if ($("#checkAll")) {
        $("#checkAll").attr('checked', false);
      }
      //destroy the popup
      $(this).dialog('destroy');
    },
    buttons: {
      'Yes': function() { //Previously it was OK
        if (fn == "reqactivate" || fn == "reqdeactivate") {
          activateDeactivateRequests(this, fn, id, mode);
        }
        else if (fn == "activate" || fn == "deactivate") {
          activateDeactivateSubjects(this, fn, id, mode);
        }
        else if (fn == "ignore" || fn == "archive") {
          ignoreArchiveMessages(this, fn, id, mode, "page");
        }else if (fn == "polldelete") {
          deletepollok(id);
        }
        else if (fn == "publish") {
          publishNewsletters(this, fn, id, mode);
        }
        else if (fn == "active" || fn == "deactive") {
                   
          activeDeactive(this, fn, id[0],id[1], mode);
        }
      },
      'No': function() { //Previously it was Cancel
        if (fn == "polldelete") {
          $(this).dialog('destroy');
          openDialog('poll/details', id, 500, 300, 'View poll');
          return false;
        }

        $('input[@name=checkBoxList]:checked').each(function(){
          this.checked = false;
        });
        if ($("#checkAll")) {
          $("#checkAll").attr('checked', false);
        }
        //destroy the popup
        $(this).dialog('destroy');
      }
    }
  });
  $('#dialog').dialog('open');
  var h = heit;
  if(buttons){
    h = heit-95;
  }else{
    h = heit-60;
  }
  $('#dialog').css({
    'overflow-y':'auto',
    'width': (wid-40)+'px',
    'height':h+'px'
  }).show();
  $('#dialog').html('<div style="padding-top:17px; padding-left:25px;">'+content+'</div>');
}

//Open the simple confirmation box for delete and other actions
function openConfirmBox (callback, width, height, title, content) {
  var wid = width;
  var heit = height;
  $('#alertdialog').dialog({
    autoOpen: false,
    width: wid,
    height: heit,
    bgiframe: true,
    resizable: false,
    title:title,
    modal: true,
    show: 'puff',
    buttons: {
      'Yes': callback, ////Previously it was OK
      'No': function() { ////Previously it was Cancel
        $('#alertdialog').dialog('destroy');
      }
    }
  })
  var img_name = 'lg_triangle_yellow_questionmark.gif';
  $('#alertdialog').show();
  $('#alertdialog').html('<div style="padding-left: 0px;"><span id="ConfirmImage" style="float: left;"><img border="0" src="'+baseurl+themeurl+'/images/'+img_name+'"/></span><span id="ConfirmContent" style="float: left; padding-left: 10px; width: '+(width-70)+'px">'+content+'</span></div>');
  $('#alertdialog').dialog('open');
  $('#alertdialog').css({
    'overflow-y':'auto',
    'width': (wid-15)+'px',
    'height':heit+'px'
  });
}

//Open the simple confirmation box for delete and other actions
function openAlertBox (width, height, title, content) {
  var wid = width;
  var heit = height;
  $('#alertdialog').css({
    'overflow-y':'auto',
    'width': (wid-15)+'px',
    'height':(heit-77)+'px'
  });
  $('#alertdialog').dialog({
    autoOpen: false,
    width: wid,
    height: heit,
    bgiframe: true,
    resizable: false,
    title:title,
    modal: true,
    //show: 'puff',
    buttons: {
      'OK': function() {
        $('#alertdialog').dialog('destroy');
      }
    }
  })
  $('#alertdialog').show();
  $('#alertdialog').html(content);
  $('#alertdialog').dialog('open');
}

function reopen_dialog(width, height, title){
  var tp = $(window).height()/2-(height/2);
  var lt = $(window).width()/2-(width/2);
  $('#dialog').css({
    'overflow':'hidden',
    'width': width/2+'px',
    'height':height/2+'px'
  });
  $('#dialog').html('<div style="padding-top:'+(height/2-27)+'px; padding-left:'+(width/2-27)+'px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading..." title="Loading... Please Wait !!!" border="0"></div>');
  $('#dialog').parent().parent().animate({
    width: width,
    height: height,
    top: tp,
    left: lt
  }, 'fast','linear',function(){
    $('#dialog').css({
      'overflow-y':'auto',
      'width': (width-16)+'px',
      'height':(height-35)+'px'
    });
  })
  $('#dialog').data('title.dialog', title);
}

function resize_dialog(width, height){
  var tp = $(window).height()/2-(height/2);
  var lt = $(window).width()/2-(width/2);
  $('#dialog').css({
    'overflow':'hidden'
  });
  $('#dialog').parent().parent().animate({
    width: width,
    height: height,
    top: tp,
    left: lt
  }, 'fast','linear',function(){
    $('#dialog').css({
      'overflow-y':'auto',
      'width': (width-16)+'px',
      'height':(height-35)+'px'
    });
  })
}

function getSelectedCheckBoxes (module_alert) {
  //Get the values of the list of checkboxes selected
  var checkbox_values = getSelectedValues();
  //return false if no checkbox is selected
  if (checkbox_values.length == 0) {
    if(module_alert=="Speciality")
      module_alert = "Specialty";

    //open the alert dialog if no checkbox is selected
    //openAlertDialog(300, 125, 'Information', 'Please select atleast one ' + module_alert, '');
    openAlertDialog(300, 125, "ErrorMessage", 'Please select atleast one ' + module_alert, '');

    return false;
  }
  //return selected values
  return checkbox_values;
}

//function to reload list through AJAX
function reloadListingData (limit, page, action, counter, url, location) {
  if (location == "popup" && page == 0) {
    page = 1;
  }
	
  if (location == "popup") {
    var selected_values = "";
    var all_values = "";
    selected_values = getSelectedValues_Popup();
    all_values = getAllValues_Popup();
  }
  //page loading animation
  pagination_loading(location);

  //Call the AJAX functionality and return the result
  if (typeof $("#hid_sort_workflow").val() == "undefined") {
    var sort = $('#hid_sort').val();
  }
  else{
    var sort = $("#hid_sort_workflow").val();
  }
  var pno = $('#hid_pageno').val();

  if (location != "popup") {
    if(action=="previous"){
      page = parseInt(pno,10)-1;
    }else if(action=="next"){
      page = parseInt(pno,10)+1;
    }
  }
	
  //remove the checkall checkbox if selected
  if ($("#checkAll")) {
    $("#checkAll").attr('checked', false);
  }
		
  $.ajax({
    type : "POST",
    url : url+"?limit="+limit+"&page="+page+"&mode=ajax"+(sort!=""?"&sorting="+sort:""),
    data : ((selected_values != "") ? ("selected_values=" + selected_values) : "") + ((all_values != "") ? ("&all_values=" + all_values) : ""),
    async : true,
    cache : false,
    success : function (msg) {
      if (location == "page") {
        $("#listingResultset").html(msg);
      }
      else if (location == "popup") {
        $("#listingResultsetPopup").html(msg);
      }
      //create pagination links through AJAX
      var str = "";
      var to = page*limit;
      //modified if the counter is less while filtering the records based on location
      if (to > counter) {
        if (location == "page") {
          counter = $("#hid_totalRec").val();
        }
        else if (location == "popup") {
          counter = $("#hid_totalRec_popup").val();
        }
      }
			
      str += '<span>Showing <b>'+(counter>0?(page-1)*limit+1:0)+'</b> to <b>'+(to>counter?counter:to)+'</b> of <b>'+counter+'</b></span>';
      if (page > 1) {
        str += '<a href="javascript:void(0)" onclick = "reloadListingData('+limit+', '+(page - 1)+', \'previous\', '+counter+', \''+url+'\', \''+location+'\')" class="red"><< Previous</a>';
      }
      if (to < counter) {
        str += '<span class="red"> |</span><a href="javascript:void(0)" onclick = "reloadListingData('+limit+', '+(page + 1)+', \'next\', '+counter+', \''+url+'\', \''+location+'\')" class="red">Next >></a>';
      }
			
      if (location == "page") {
        if ($("#pagingdivtop")) $("#pagingdivtop").html(str);
        if ($("#pagingdivbottom")) $("#pagingdivbottom").html(str);
        $('#hid_pageno').val(page);
      }
      else if (location == "popup") {
        if ($("#pagingdivtoppopup")) $("#pagingdivtoppopup").html(str);
        if ($("#pagingdivbottompopup")) $("#pagingdivbottompopup").html(str);
      }
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

//Pagination loading animation
function pagination_loading (location){
  if (location == "page") {
    $("#listingResultset").html('<div style="padding-top:150px;padding-bottom:150px;text-align:center;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading..." /></div>');
    $("#pagingdivtop").html("");
    $("#pagingdivbottom").html("");
  }
  else if (location == "popup") {
    $("#listingResultsetPopup").html('<div style="padding-top:150px;padding-bottom:150px;text-align:center;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading..." /></div>');
    $("#pagingdivtoppopup").html("");
    $("#pagingdivbottompopup").html("");
  }
}

//Function to apply style for success and error messages in popup
function styleStatusMessages (message, id, result) {
  if (result == "success") {
    $("#"+id).removeClass("popuperrorMessage");
    $("#"+id).addClass("popupsuccessMessage");
    $("#"+id).show();
  //$("#"+id).fadeOut(3000);
  }
  else if (result == "failure") {      
    $("#"+id).removeClass("popupsuccessMessage");
    $("#"+id).addClass("popuperrorMessage");
    $("#"+id).show();
  //$("#"+id).fadeOut(3000);
  }
  if(result == "" && message == "")
    $("#"+id).fadeOut(0);
  $("#"+id).html(message);
}

//implementation of closeValidate
function closeValidate(obj){
  $(obj).parent().parent().slideUp('fast');
}

//Function to sort columns
function sortColumn(module, sort){
  $("#listingResultset").html('<div style="padding-top:150px;padding-bottom:150px;text-align:center;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading..." /></div>');
  $("#pagingdivtop").html("");
  $("#pagingdivbottom").html("");

  var limit = 10;
  if (typeof $("#hid_sort_workflow").val() == "undefined") {
    var hid_sort = $('#hid_sort').val();
  }
  else{
    var hid_sort = $("#hid_sort_workflow").val();
  }
  var orig_sort = sort;
		
  if (module == "manage.subjects") {
    module = "manage_subjects";
  }
  var data = eval("filterdata_"+module+"();");  
  if(hid_sort){
    hid_sort = hid_sort.split(",");
    if(hid_sort[1]==sort){
      if(hid_sort[0]=="ascending")
        sort = ["descending",sort];
      else
        sort = ["ascending",sort];
    }else{
      sort = ["ascending",sort];
      $('#srt_'+hid_sort[1]).attr('class','sortNone');
    }
  }else
    sort = ["ascending",sort];

  var urls = module;
  var action = "";
  //modified for contactus archived
  if(module == "requests") {
    urls = "request/actions/manage.requests";
    action = "manage.requests";
  }
  else if (module == "archived") {
    urls = "actions/filter/"+module;
    action = "archived";
  }
  else if (module == "manage_subjects") {
    urls = "subjects/actions/manage.subjects";
    action = "manage.subjects";
  }
  else if(module == "testimonial_archived"){
    urls = "actions/filter/archived";
  }
  else if(module == "view_speciality"){
    urls = "actions/filter/view_speciality";
  }
  else if(module == "view_invites"){
    urls = "actions/filter/view_invites";
  }
  else if(module == "view_group"){
    urls = "actions/filter/view_group";
  }
  else if(module == "view_warmhandoff"){
    var base=location.href;
    var ind = base.lastIndexOf('/');
    var pathurl=base.substr(0,ind);   
    var b=pathurl.replace("handoffreports","");
    urls = b+"actions/filter/view_warmhandoff";
   
  }
  else if(module == "crm"){
    urls = "filter";
  }
  else if(module == "webproxy"){
    urls = module+"/filter";
  }
  else if(module == "categories"){
    urls = "actions/filter/categoriessearch";
    action = "categories";
  }
  else if(module == "stores"){
    urls = "actions/filter/storessearch";
    action = "stores";
  }
  else if (module == "workflow") {
    urls = baseurl + "workflow/actions/filter";
  }
  else if (module == "groups") {
    urls = baseurl + "workflow/actions/groups";
  }
  else if (module == "workflowlist") {
    urls = baseurl + "workflow/list/actions";
  }
  else {
    urls = module+"/actions/filter";
  }

  $.ajax({
    type : "POST",
    url : urls,
    data: "limit=" + limit + "&page=1&sorting=" + sort + data,
    async : true,
    cache : false,
    success : function (msg) {
      $("#listingResultset").html(msg);
      $('#srt_'+orig_sort).attr('class', sort[0]=="ascending"?"sortAsc":"sortDsc");
			
      if (typeof $("#hid_sort_workflow").val() == "undefined") {
        $('#hid_sort').val(sort);
      }
      else{
        $('#hid_sort_workflow').val(sort);
      }
      
      refresh_pagination(1, action, module);
      $('#checkAll').attr('checked', false);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

//Function to refresh the pagination after sorting
function refresh_pagination(pageno, action, module){	
  var limit = $('#hid_limit').val();
  var page = pageno;
  var counter = $('#hid_totalRec').val();
  if(counter>0){
    var str="";
    var to = page*limit;
    str += '<span>Showing <b>'+(counter>0?(page-1)*limit+1:0)+'</b> to <b>'+(to>counter?counter:to)+'</b> of <b>'+counter+'</b></span>';
    if (page > 1) {
      if (module == "contactus" || module == "archived" || module == "fulfillment") {
        str += '<a href="javascript:void(0)" onclick = "applyMessageFilterAction('+(page-1)+', \''+action+'\')" class="red"><< Previous</a>';
      }
      else if (module == "manage_subjects") {
        str += '<a href="javascript:void(0)" onclick = "applySubjectsFilterAction('+(page-1)+', \'manage.subjects\')" class="red"><< Previous</a>';
      }
      else if (module == "newsletter") {
        str += '<a href="javascript:void(0)" onclick = "applyNewsletterFilterAction('+(page-1)+')" class="red"><< Previous</a>';
      }
      else if (module == "crm") {
        str += ' <span class="red"> |</span><a href="javascript:void(0)" onclick = "applyEventTypeFilterAction('+(page-1)+')" class="red"><< Previous</a>';
      }
      else if (module == "webproxy") {
        str += ' <span class="red"> |</span><a href="javascript:void(0)" onclick = "applyWebproxyFilterAction('+(page-1)+')" class="red"><< Previous</a>';
      }
      else if (module == "categories") {
        str += ' <span class="red"> |</span><a href="javascript:void(0)" onclick = "applyCategoriesFilterAction('+(page-1)+')" class="red"><< Previous</a>';
      }
      else if (module == "stores") {
        str += ' <span class="red"> |</span><a href="javascript:void(0)" onclick = "applyStoresFilterAction('+(page-1)+')" class="red"><< Previous</a>';
      }
      else if (module == "workflow") {
        str += ' <span class="red"> |</span><a href="javascript:void(0)" onclick = "searchapplyAction('+(page-1)+')" class="red"><< Previous</a>';
      }
      else if (module == "groups") {
        str += ' <span class="red"> |</span><a href="javascript:void(0)" onclick = "applyWorkflowAction('+(page-1)+')" class="red"><< Previous</a>';
      }
      else if (module == "workflowlist") {
        str += ' <span class="red"> |</span><a href="javascript:void(0)" onclick = "applyWorkflowListAction('+(page-1)+')" class="red"><< Previous</a>';
      }
      else {
        str += '<a href="javascript:void(0)" onclick = "applyAction('+(page-1)+',\''+action+'\')" class="red"><< Previous</a>';
      }
    }

    if (to < counter) {
      if (module == "contactus" || module == "archived" || module == "fulfillment") {
        str += ' <span class="red"> |</span><a href="javascript:void(0)" onclick = "applyMessageFilterAction('+(page+1)+', \''+action+'\')" class="red">Next >></a>';
      }
      else if (module == "manage_subjects") {
        str += ' <span class="red"> |</span><a href="javascript:void(0)" onclick = "applySubjectsFilterAction('+(page+1)+', \'manage.subjects\')" class="red">Next >></a>';
      }
      else if (module == "newsletter") {
        str += ' <span class="red"> |</span><a href="javascript:void(0)" onclick = "applyNewsletterFilterAction('+(page+1)+')" class="red">Next >></a>';
      }
      else if (module == "view_speciality") {
        str += ' <span class="red"> |</span><a href="javascript:void(0)" onclick = "applyspecialityAction('+(page+1)+', \'view_speciality\')" class="red">Next >></a>';
      }
      
      else if (module == "view_group") {
        str += ' <span class="red"> |</span><a href="javascript:void(0)" onclick = "applygroupAction('+(page+1)+', \'view_group\')" class="red">Next >></a>';
      }
      
      else if (module == "view_warmhandoff") {
        str += ' <span class="red"> |</span><a href="javascript:void(0)" onclick = "applywarmhandoffaction('+(page+1)+', \'view_warmhandoff\')" class="red">Next >></a>';
      }
      
      else if (module == "requests") {
        str += ' <span class="red"> |</span><a href="javascript:void(0)" onclick = "applyRequestsFilterAction('+(page+1)+', \''+action+'\')" class="red">Next >></a>';
      }
      else if (module == "crm") {
        str += ' <span class="red"> |</span><a href="javascript:void(0)" onclick = "applyEventTypeFilterAction('+(page+1)+')" class="red">Next >></a>';
      }
      else if (module == "webproxy") {
        str += ' <span class="red"> |</span><a href="javascript:void(0)" onclick = "applyWebproxyFilterAction('+(page+1)+')" class="red">Next >></a>';
      }
      else if (module == "categories") {
        str += ' <span class="red"> |</span><a href="javascript:void(0)" onclick = "applyCategoriesFilterAction('+(page+1)+', \''+action+'\')" class="red">Next >></a>';
      }
      else if (module == "stores") {
        str += ' <span class="red"> |</span><a href="javascript:void(0)" onclick = "applyStoresFilterAction('+(page+1)+')" class="red">Next >></a>';
      }
      else if (module == "workflow") {
        str += ' <span class="red"> |</span><a href="javascript:void(0)" onclick = "searchapplyAction('+(page+1)+')" class="red">Next >></a>';
      }
      else if (module == "groups") {
        str += ' <span class="red"> |</span><a href="javascript:void(0)" onclick = "applyWorkflowAction('+(page+1)+')" class="red">Next >></a>';
      }
      else if (module == "workflowlist") {
        str += ' <span class="red"> |</span><a href="javascript:void(0)" onclick = "applyWorkflowListAction('+(page+1)+')" class="red">Next >></a>';
      }
      else {
        str += ' <span class="red"> |</span><a href="javascript:void(0)" onclick = "applyAction('+(page+1)+',\''+action+'\')" class="red">Next >></a>';
      }
    }

    $("#pagingdivtop").html(str);
    $("#pagingdivbottom").html(str);
  }else{
    $("#pagingdivtop").html("");
    $("#pagingdivbottom").html("");
  }
}

//Function to select a site
function selectSite(siteId, siteName) {
 
  //Set the site context
 
  SetCookie('CURRENT_CONTENT_SITE_ID', siteId, 1);
  SetCookie('CURRENT_CONTENT_SITE_NAME', siteName, 1);
  
  //Remove legal entity context, if exists
  
  SetCookie('CURRENT_CONTENT_LEGAL_ENTITY_ID', 0, -1);
  SetCookie('CURRENT_CONTENT_LEGAL_ENTITY_NAME', '', -1);
  
  window.location.href=baseurl;
}

//Function to select a legal entity
function selectLegalEntity(legalEntityId, legalEntityName) {
 
  //Set the legal entity context
  
  SetCookie('CURRENT_CONTENT_LEGAL_ENTITY_ID', legalEntityId, 1);
  SetCookie('CURRENT_CONTENT_LEGAL_ENTITY_NAME', legalEntityName, 1);
  
  //Remove the site context, if exists
  
  SetCookie('CURRENT_CONTENT_SITE_ID', 0, -1);
  SetCookie('CURRENT_CONTENT_SITE_NAME', '', -1);
  
  window.location.href=baseurl;
}

//Function to create a cookie
function SetCookie(cookieName,cookieValue,nDays) {
  var today = new Date();
  var expire = new Date();
  if (nDays==null || nDays==0) nDays=1;
  expire.setTime(today.getTime() + 3600000*24*nDays);
  document.cookie = cookieName+"="+escape(cookieValue)
  + ";expires="+expire.toGMTString()
  + ";path= /";
}

//Fucntion to implement the filtered listbox
function filteredList(id, optionscopy ) {
  // This method removes all of the options from the select list,
  // then adds only the options that match the pattern regexp.
  // It also unselects all of the options.
  var loop=0, index=0, regexp, e;
  var selectObj = $('#filter_sel_'+id).get(0);
  var inputObj = $('#filter_inp_'+id);
  // This variable for In-case sensitive
  var flags = 'i';
  if (selectObj==null || inputObj==null) return false;
  if (!selectObj.options) return false;
  var pattern = inputObj.val();
  // Clear the select list so nothing is displayed
  selectObj.options.length = 0;

  try {
    // Initialize the regexp
    regexp = new RegExp(pattern, flags);
  } catch(e) {
    return true;
  }

  // Loop through the entire select list and
  // add the matching items to the select list
  for (loop=0; loop < optionscopy.length; loop++) {
    // This is the option that we're currently testing
    var option = optionscopy[loop];
    // Check if we have a match
    if (regexp.test(option)) {
      // We have a match, so add this option to the select list
      // and increment the index
      selectObj.options[index++] = new Option(option, option, false);
    }
  }
  return true;
}

//Function to strip HTML tags
function stripHTML(oldString) {
  var newString = "";
  var inTag = false;
  for(var i = 0; i < oldString.length; i++) {
    if(oldString.charAt(i) == '<') inTag = true;
    if(oldString.charAt(i) == '>') {
      if(oldString.charAt(i+1)=="<") {
      //dont do anything
      }
      else {
        inTag = false;
        i++;
      }
    }
    if(!inTag)
      newString += oldString.charAt(i);
  }
	
  newString = newString.replace(/&nbsp;/g, "")
  return newString;
}

//function to handle AJAX error
function handleRequestError (resp) {
  var response = resp.responseText;
  
  if (response.search(/Access Denied/) != -1) {
    $('#dialog').html("You are not authorized to access this page.");
  }
  /*else if (response == "" && resp.status == 0) {
    //Nothing to do
  }*/
  else {
    $("#dialog").dialog("destroy");
    window.location.href = baseurl + 'handle/error';
  }
}

//Function to implement source to taget listbox
function f_optionMove(s_from, s_to) {
  var e_from = $("#"+s_from).get(0);
  var e_to   = $("#"+s_to).get(0);
  var n_moved = 0;
  for (var i = 0; i < e_from.options.length; i++) {
    if (e_from.options[i].selected) {
      e_to.options[e_to.options.length] = new Option(e_from.options[i].text, e_from.options[i].value);
      n_moved++;
    }
    else if (n_moved)
      e_from.options[i - n_moved] = new Option(e_from.options[i].text, e_from.options[i].value);
  }
  if (n_moved)
    e_from.options.length = e_from.options.length - n_moved;
  else
    return;
}

//Function to validate email address
function validateEmail(elementValue){
  var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
  return emailPattern.test(elementValue);
}

// Function to validate URL
function isUrl(elementValue) {
  var regexp = /(http|https):\/\/[A-Za-z0-9\.-]{3,}\.[A-Za-z]{3}/;
  return regexp.test(elementValue);
}

// Function to validate WEBSITEURL
function isWeburl(elementValue) {
  if(elementValue.indexOf("http://")>-1 || elementValue.indexOf("https://")>-1)
    return true;
  else
    return false;
}

//Function to validate activation date and expiration date NOTE:Date should be in the format YYYY/MM/DD
function fromGreaterThanTo (from_date, to_date) {
  var fromDate = new Date(from_date); // creates a new Date for the 1st June 2005
  var toDate = new Date(to_date); // creates a new Date representing today
  if (fromDate <= toDate) {
    return true;
  }
  return false;
}

// Function to validate a regular expression regexp = ^[A-Za-z]{1,20}$ allow up to 20 alphabetic characters.
function TestRegExp(objValue, strRegExp){
  var ret = true;
  if( objValue.length > 0 && !objValue.match(strRegExp) ){
    ret = false;
  }//if
  return ret;
}

function unselectCheckall(){
  var checked_status = true;
  $("input[@name=checkBoxList]").each(function() {
    if(this.checked==false){
      checked_status = false;
    }
  });
  if(checked_status==false) {
    $('input[name=checkAll]').attr('checked', false);
  }else{
    $('input[name=checkAll]').attr('checked', true);
  }
}
//Function to get the Graph in a dialog box
function graphInDialog (id) {
  //prepare the field values for filtering
  var start_date = $.trim($("#edit-start-date").val());
  var end_date = $.trim($("#edit-end-date").val());
  $.ajax({
    type : "POST",
    url : baseurl+'webmetrics/graph/'+id,
    data : "start_date="+start_date+"&end_date="+end_date,
    cache : false,
    success : function (res) {
      $('#dialog').html(res);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

function enter_handle_go(event){
  if(event.keyCode && event.keyCode==13){
    searchGroup('go');
  }else if(event.which && event.which==13){
    searchgroup('go');
  }
}

/**
 * Append placeholders to the email template content
 */ 
function contentAddText (txt) { 
  var text = $('#edit-email-template').val();
  var text_first = text.substring(0, (parseInt($("#edit-cursor-position").val())));
  var text_insert = txt;
  var text_last = text.substring(parseInt($("#edit-cursor-position").val()));
  $('#edit-email-template').val(text_first + text_insert + text_last);
}

/**
 * Function to get the character position
 */
function getCaret (el) {
  if (el.selectionStart) {
    return el.selectionStart;
  } else if (document.selection) {
    el.focus();

    var r = document.selection.createRange();
    if (r == null) {
      return 0;
    }

    var re = el.createTextRange(),
    rc = re.duplicate();
    re.moveToBookmark(r.getBookmark());
    rc.setEndPoint('EndToStart', re);

    return rc.text.length;
  } 
  return 0;
}


function criteriaDialog(id){
  $.ajax({
    type : "GET",
    url  : baseurl+'physician_locator/add_criteria/'+id,
    cache : false,
    success : function (res) {
      $('#dialog').html(res);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

var ckeditor;
function fckeditor(id){
  if(!ckeditor){
    ckeditor = CKEDITOR.replace(id,{
      skin : 'v2',
      resize_enabled:false,
      enterMode: Number(2),
      removePlugins : 'elementspath,save,forms,font,format,smiley,maximize,showblocks,about,stylescombo,pagebreak,flash'
    });
  }else{
    if (CKEDITOR.instances[id]) {
      CKEDITOR.remove(CKEDITOR.instances[id]);
    }
    ckeditor=null;
    ckeditor = CKEDITOR.replace(id,{
      skin : 'v2',
      resize_enabled:false,
      enterMode: Number(2),
      removePlugins : 'elementspath,save,forms,font,format,smiley,maximize,showblocks,about,stylescombo,pagebreak,flash'
    });
  }
  $('.ui-dialog').css("filter","");
}